<template>
  <div class="my-registrations">
    <div class="page-header">
      <h2>我的活动</h2>
    </div>

    <el-card class="filter-card">
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="活动状态">
            <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="待参加" value="UPCOMING" />
              <el-option label="进行中" value="ACTIVE" />
              <el-option label="已结束" value="COMPLETED" />
              <el-option label="已取消" value="CANCELLED" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon> 筛选
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <div v-loading="loading" class="registrations-content">
      <div v-if="!loading && registrations.length === 0" class="empty-container">
        <el-empty description="暂无活动报名记录">
          <el-button type="primary" @click="goToActivities">浏览活动</el-button>
        </el-empty>
      </div>
      
      <div v-else class="registrations-list">
        <el-row :gutter="20">
          <el-col v-for="item in registrations" :key="item.id" :xs="24" :sm="12" :md="8" :lg="6">
            <el-card
              class="registration-card"
              :class="{ 'cancelled': item.activity.status === 'CANCELLED' }"
              shadow="hover"
            >
              <div class="activity-image">
                <el-image
                  :src="item.activity.imageUrl || defaultImage"
                  fit="cover"
                  @error="handleImageError"
                />
                <div class="activity-status">
                  <el-tag :type="getStatusType(item.activity)" size="small">
                    {{ getStatusText(item.activity) }}
                  </el-tag>
                </div>
              </div>
              
              <div class="activity-info">
                <h3 class="activity-title" @click="viewActivityDetail(item.activity.id)">
                  {{ item.activity.title }}
                </h3>
                
                <div class="activity-meta">
                  <div class="meta-item">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatDateTime(item.activity.startTime) }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ item.activity.location }}</span>
                  </div>
                </div>
                
                <div class="registration-meta">
                  <div class="meta-item">
                    <span class="label">报名时间:</span>
                    <span>{{ formatDateTime(item.registrationTime) }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="label">出席状态:</span>
                    <span>{{ item.attended ? '已出席' : '未出席' }}</span>
                  </div>
                </div>
                
                <div class="card-actions">
                  <template v-if="canCancel(item)">
                    <el-button
                      type="danger"
                      size="small"
                      :loading="item.cancelling"
                      @click="confirmCancelRegistration(item)"
                    >
                      取消报名
                    </el-button>
                  </template>
                  
                  <template v-if="canGiveFeedback(item)">
                    <el-button
                      type="primary"
                      size="small"
                      @click="showFeedbackDialog(item)"
                    >
                      {{ item.hasFeedback ? '查看评价' : '评价活动' }}
                    </el-button>
                  </template>
                  
                  <el-button
                    type="info"
                    size="small"
                    plain
                    @click="viewActivityDetail(item.activity.id)"
                  >
                    查看详情
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[8, 16, 24, 32]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 活动评价对话框 -->
    <el-dialog
      v-model="feedbackDialogVisible"
      :title="currentRegistration && currentRegistration.hasFeedback ? '我的评价' : '评价活动'"
      width="500px"
    >
      <div v-if="currentRegistration">
        <el-form :model="feedbackForm" :rules="feedbackRules" ref="feedbackFormRef" label-width="80px">
          <el-form-item label="评分" prop="rating">
            <el-rate
              v-model="feedbackForm.rating"
              :disabled="currentRegistration.hasFeedback"
              show-score
              text-color="#ff9900"
            />
          </el-form-item>
          
          <el-form-item label="评价" prop="comment">
            <el-input
              v-model="feedbackForm.comment"
              type="textarea"
              :rows="4"
              :disabled="currentRegistration.hasFeedback"
              placeholder="请分享您对此活动的想法与建议..."
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="feedbackDialogVisible = false">关闭</el-button>
            <el-button
              v-if="!currentRegistration.hasFeedback"
              type="primary"
              :loading="submittingFeedback"
              @click="submitFeedback"
            >
              提交评价
            </el-button>
          </span>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getMyRegistrations, cancelRegistration, submitFeedback as submitFeedbackAPI } from '@/api/club';
import { formatDateTime } from '@/utils/format';
import { Calendar, Location, Search, Refresh } from '@element-plus/icons-vue';

const router = useRouter();
const loading = ref(false);
const registrations = ref([]);
const total = ref(0);
const defaultImage = 'https://via.placeholder.com/400x225?text=活动封面';

// 分页
const pagination = reactive({
  page: 1,
  size: 8
});

// 筛选表单
const filterForm = reactive({
  status: ''
});

// 获取报名记录
const fetchRegistrations = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page - 1,
      size: pagination.size,
      status: filterForm.status || null
    };
    
    const res = await getMyRegistrations(params);
    
    // 添加UI状态到记录
    registrations.value = (res.registrations || []).map(reg => ({
      ...reg,
      cancelling: false,
      hasFeedback: !!reg.feedback
    }));
    
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取报名记录失败', error);
    ElMessage.error('获取报名记录失败');
  } finally {
    loading.value = false;
  }
};

// 筛选处理
const handleFilter = () => {
  pagination.page = 1;
  fetchRegistrations();
};

// 重置筛选
const resetFilter = () => {
  filterForm.status = '';
  pagination.page = 1;
  fetchRegistrations();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size;
  fetchRegistrations();
};

const handleCurrentChange = (page) => {
  pagination.page = page;
  fetchRegistrations();
};

// 处理图片错误
const handleImageError = (e) => {
  e.target.src = defaultImage;
};

// 查看活动详情
const viewActivityDetail = (id) => {
  router.push(`/club/detail/${id}`);
};

// 去浏览活动页面
const goToActivities = () => {
  router.push('/club/list');
};

// 获取活动状态类型
const getStatusType = (activity) => {
  if (!activity) return '';
  
  if (activity.status === 'CANCELLED') {
    return 'danger';
  }
  
  const now = new Date();
  const startTime = new Date(activity.startTime);
  const endTime = new Date(activity.endTime);
  
  if (endTime < now) {
    return 'info';  // 已结束
  } else if (startTime > now) {
    return 'primary';  // 未开始
  } else {
    return 'success';  // 进行中
  }
};

// 获取活动状态文本
const getStatusText = (activity) => {
  if (!activity) return '';
  
  if (activity.status === 'CANCELLED') {
    return '已取消';
  }
  
  const now = new Date();
  const startTime = new Date(activity.startTime);
  const endTime = new Date(activity.endTime);
  
  if (endTime < now) {
    return '已结束';
  } else if (startTime > now) {
    return '未开始';
  } else {
    return '进行中';
  }
};

// 是否可以取消报名
const canCancel = (registration) => {
  if (!registration || !registration.activity) return false;
  
  const now = new Date();
  const startTime = new Date(registration.activity.startTime);
  
  // 只有活动未开始且未被取消的情况下才能取消报名
  return startTime > now && registration.activity.status !== 'CANCELLED';
};

// 是否可以评价活动
const canGiveFeedback = (registration) => {
  if (!registration || !registration.activity) return false;
  
  const now = new Date();
  const endTime = new Date(registration.activity.endTime);
  
  // 只有活动已结束且非取消状态才能评价
  return endTime < now && registration.activity.status !== 'CANCELLED';
};

// 确认取消报名
const confirmCancelRegistration = async (registration) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消此活动的报名吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 设置loading状态
    registration.cancelling = true;
    
    await cancelRegistration(registration.id);
    ElMessage.success('取消报名成功');
    
    // 刷新列表
    fetchRegistrations();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败', error);
      ElMessage.error('取消报名失败');
    }
    
    // 清除loading状态
    if (registration) {
      registration.cancelling = false;
    }
  }
};

// 评价相关
const feedbackDialogVisible = ref(false);
const currentRegistration = ref(null);
const submittingFeedback = ref(false);
const feedbackFormRef = ref(null);

const feedbackForm = reactive({
  rating: 5,
  comment: ''
});

const feedbackRules = {
  rating: [
    { required: true, message: '请给活动评分', trigger: 'change' }
  ],
  comment: [
    { required: true, message: '请填写评价内容', trigger: 'blur' },
    { min: 5, max: 500, message: '评价长度在 5 到 500 个字符', trigger: 'blur' }
  ]
};

// 显示评价对话框
const showFeedbackDialog = (registration) => {
  currentRegistration.value = registration;
  
  // 如果已有评价，显示已有评价
  if (registration.hasFeedback && registration.feedback) {
    feedbackForm.rating = registration.feedback.rating || 5;
    feedbackForm.comment = registration.feedback.comment || '';
  } else {
    // 否则初始化表单
    feedbackForm.rating = 5;
    feedbackForm.comment = '';
  }
  
  feedbackDialogVisible.value = true;
};

// 提交评价
const submitFeedback = async () => {
  if (!feedbackFormRef.value) return;
  
  await feedbackFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submittingFeedback.value = true;
    try {
      await submitFeedbackAPI(
        currentRegistration.value.activity.id,
        feedbackForm.comment,
        feedbackForm.rating
      );
      
      ElMessage.success('评价提交成功');
      feedbackDialogVisible.value = false;
      
      // 更新本地数据和刷新列表
      if (currentRegistration.value) {
        currentRegistration.value.hasFeedback = true;
        currentRegistration.value.feedback = {
          rating: feedbackForm.rating,
          comment: feedbackForm.comment
        };
      }
      
      fetchRegistrations();
    } catch (error) {
      console.error('提交评价失败', error);
      ElMessage.error('提交评价失败');
    } finally {
      submittingFeedback.value = false;
    }
  });
};

onMounted(() => {
  fetchRegistrations();
});
</script>

<style scoped>
.my-registrations {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 1.8rem;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.registrations-content {
  min-height: 400px;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.registrations-list {
  margin-top: 20px;
}

.registration-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
  overflow: hidden;
}

.registration-card:hover {
  transform: translateY(-5px);
}

.registration-card.cancelled {
  opacity: 0.7;
}

.activity-image {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.activity-image .el-image {
  width: 100%;
  height: 100%;
}

.activity-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.activity-info {
  padding: 12px;
}

.activity-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.activity-title:hover {
  color: #409EFF;
}

.activity-meta {
  margin-bottom: 10px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 5px;
  font-size: 13px;
  color: #606266;
}

.registration-meta {
  padding: 10px 0;
  border-top: 1px dashed #ebeef5;
  border-bottom: 1px dashed #ebeef5;
  margin-bottom: 10px;
}

.label {
  color: #909399;
  margin-right: 5px;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style> 